package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    //依赖注入
    @Reference
    private UserService userService;

    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            //从授权框架上下文获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //再从认证对象获取授权框架用户对象User
            User user = (User)authentication.getPrincipal();
            //最后获取用户名
            String username = user.getUsername();
            //若获取user成功, 返回成功操作, 并返回用户名
            return new Result(true, MessageConst.ACTION_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            //若获取user对象为null, 返回操作失败
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    @RequestMapping("/loginSuccess")
    public Result loginSuccess(){
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,"登录失败");
    }

    @RequestMapping("/login")
    public Result login(String username, String password){
        System.out.println("oms backend====u:"+username+" ,p:"+password);
        if (userService.login(username, password)){
            System.out.println("login ok!!!");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            System.out.println("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
